home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: about free()
- Date: Wed, 28 Feb 96 12:38:38 GMT
- Organization: none
- Message-ID: <825511118snz@genesis.demon.co.uk>
- References: <31333454.167E@mashie.ece.jhu.edu>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <31333454.167E@mashie.ece.jhu.edu>
- chenyang@mashie.ece.jhu.edu "Chenyang Xu" writes:
-
- >Hi, there,
- >
- > I have a simple question here.
- >
- > I have a function say newarrary() which mallocs an array inside and
- >returns a pointer to this arrary. In another function foo.c, the result
- >of newarray() is assigned to a pointer ptr. Now after some operations on
- >this array. I use free(ptr) to free the memory allocated by newarrary().
- >My question is whould this cause a problem, since free() is not freeing
- >the same pointer which is allocated by the malloc() although this
- >pointer point to the same memory.
-
- All that matters is the value of the pointer you pass to free i.e. what
- it points to. For example:
-
- ...
-
- {
- char *ptr1 = malloc(1000);
-
- if (ptr1 != NULL) {
- char *ptr2 = ptr1 + 123;
-
- free(ptr2 - 123);
- }
- }
-
- This is perfectly legal. The pointer passed to free has the same value as
- that returned by malloc and wasn't previously passed to free. After the call
- to free() the values of both ptr1 and ptr2 are invalid since they pointed to
- an object that has been freed.
-
- Note that in the example above:
-
- free(ptr2);
-
- is illegal since ptr2 does not contain a value returned by malloc.
-
- free(ptr2-123);
- free(ptr);
-
- is illegal because it tries to free the same object twice.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-